package we.database.membase;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.util.ArrayList;

import we.common.CCommonHandler;

import we.config.CConfigHandler;

import we.database.IDataController;

import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.MemcachedClient;


public class MembaseDataController implements IDataController {
    static MembaseDataController _instance;
    static final Object lock = new Object();
    MemcachedClient cacheCli;
    MemcachedClient dataCli;

    private MembaseDataController() {
        try {
            ArrayList<InetSocketAddress> dataServers =
                new ArrayList<InetSocketAddress>();
            ArrayList<InetSocketAddress> cacheServers =
                new ArrayList<InetSocketAddress>();
            dataServers.add(new InetSocketAddress(CConfigHandler.instance().get("dservers"),
                                                  CConfigHandler.instance().getLong("dport").intValue()));
            cacheServers.add(new InetSocketAddress(CConfigHandler.instance().get("cservers"),
                                                   CConfigHandler.instance().getLong("cport").intValue()));

            ConnectionFactory factory = new DefaultConnectionFactory();
            this.dataCli = new MemcachedClient(factory, dataServers);
            this.cacheCli = new MemcachedClient(factory, cacheServers);
        } catch (IOException e) {
            CCommonHandler.writeErrLog(e);
            // TODO
            CCommonHandler.writeErrLog(e);
        }
    }

    public static MembaseDataController instance() {
        if (_instance == null) {
            synchronized (lock) {
                if (_instance == null) {
                    _instance = new MembaseDataController();
                }
            }
        }
        return _instance;
    }


    public Object get(String name) {
        return dataCli.get(name);
    }

    public void set(String name, Object data) {
        dataCli.set(name, 0, data);
    }

    public Object getCache(String name) {
        return cacheCli.get(name);
    }

    public void setCache(String name, int expire, Object data) {
        cacheCli.set(name, expire, data);
    }
}
